/**
 * Copyright (C), 2017-2018, XXX有限公司
 * FileName: UnitPanel2
 * Author:   zengjian
 * Date:     2018/8/14 11:01
 * Description: 单元测试生成面板
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package org.yinxue.swing.unit.main;

import org.yinxue.swing.core.panel.YxTextArea;
import org.yinxue.swing.core.standard.YxPanel;
import org.yinxue.swing.core.standard.YxStructure;
import org.yinxue.swing.core.util.LogUtil;
import org.yinxue.swing.core.util.SwingUtils;
import org.yinxue.swing.unit.constant.UserConfig;
import org.yinxue.swing.unit.context.Context;
import org.yinxue.swing.unit.filter.JavaFilter;
import org.yinxue.swing.unit.util.FileUtil;
import org.yinxue.swing.unit.util.UnitUtil;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import static javax.swing.WindowConstants.HIDE_ON_CLOSE;

/**
 * 〈单元测试生成面板〉<br>
 * 〈一句话描述〉
 *
 * @author zengjian
 * @create 2018/8/14 11:01
 */
public class UnitPanel2 extends YxPanel implements YxStructure {

    JPanel topButton;
    JLabel jLabel_project;
    JTextField jText_inputpath;

    JButton jButton_choose;
    JButton jButton_open;
    JButton jButton_diy;
    JButton jButton_generate;

    JLabel jLabel_unit;
    JComboBox<String> jComboBox_unitType;

    JPanel jPanel_operate;
    JLabel jLabel_operate;
    JComboBox jComboBox_operateType;

    JCheckBox jCheckBox_isPojo;

    YxTextArea topInput;
    YxTextArea downOutput;

    YxTextArea rightInfo;

    public UnitPanel2() {
        super();
    }

    @Override
    public void init() {
        topButton = createYxPanel();
        jLabel_project = createLabel("项目路径:");
        jText_inputpath = createTextField(10);
        jButton_choose = createButton("选择路径", 110, 30);

        jButton_open = createButton("开启容器", 110, 30);
        jButton_diy = createButton("自定义参数", 110, 30);
        jButton_generate = createButton("一键执行", 110, 30);

        jLabel_unit = createLabel("单元测试类型:");

        Font timeNewRoman = new Font("Timenew Romans", Font.PLAIN, 12);
        jComboBox_unitType = createComboBox("Mockito", "JUnit", "SpringTest");
        jComboBox_unitType.setPreferredSize(new Dimension(130, 25));
        jComboBox_unitType.setFont(timeNewRoman);


        jPanel_operate = createFlowPanel();
        ;
        jLabel_operate = createLabel("生成方式:");

        jComboBox_operateType = createComboBox("单个生成", "批量生成", "批量回滚");
        jComboBox_operateType.setPreferredSize(new Dimension(130, 25));
        jComboBox_operateType.setFont(timeNewRoman);

        jCheckBox_isPojo = createCheckBox("强制实体类");

        topInput = creaetYxTextArea();
        downOutput = creaetYxTextArea();
        rightInfo = creaetYxTextArea();

        jText_inputpath.setFont(timeNewRoman);
        jText_inputpath.setText(UserConfig.getUserProjectPath());
    }


    @Override
    public void position() {
        // 面板排布
        add(topButton, refreshPosition(0, 0, 2, 1, 1, 0, GridBagConstraints.HORIZONTAL));
        add(topInput, refreshPosition(0, 1, 1, 1, 1, 1, GridBagConstraints.BOTH));
        add(downOutput, refreshPosition(0, 2, 1, 1, 1, 1, GridBagConstraints.BOTH));
        add(rightInfo, refreshPosition(1, 1, 1, 2, 0, 0, GridBagConstraints.BOTH));


        jPanel_operate.add(jLabel_operate);
        jPanel_operate.add(jComboBox_operateType);
        jPanel_operate.add(jCheckBox_isPojo);

        Dimension size = new Dimension(200, 400);
        rightInfo.setPreferredSize(size);
        rightInfo.setMaximumSize(size);
        rightInfo.setMinimumSize(size);


        GridBagConstraints g = new GridBagConstraints();
        g.insets = new Insets(5, 5, 5, 5);
        topButton.setBorder(BorderFactory.createEtchedBorder());
        g.gridx = 0;
        g.gridy = 0;
        topButton.add(jLabel_project, g);

        g.gridx = 1;
        g.weightx = 1;
        g.fill = GridBagConstraints.HORIZONTAL;
        g.gridwidth = 2;
        topButton.add(jText_inputpath, g);

        g.weightx = 0;
        g.gridwidth = 1;
        g.gridx = 3;
        topButton.add(jButton_choose, g);

        g.gridx = 4;
        topButton.add(jButton_open, g);

        g.gridx = 0;
        g.gridy = 1;
        topButton.add(jLabel_unit, g);

        g.gridx = 1;
        topButton.add(jComboBox_unitType, g);


        g.gridx = 2;
        g.weightx = 1;
        g.fill = GridBagConstraints.HORIZONTAL;
        topButton.add(jPanel_operate, g);

        g.weightx = 0;
        g.gridx = 3;
        topButton.add(jButton_diy, g);

        g.gridx = 4;
        topButton.add(jButton_generate, g);

    }


    @Override
    public void action() {

        topInput.append(Context.config().defaultUnitCode);
        rightInfo.append("我是单元测试编写小助手，来试试我的[一键执行]吧！\n");


        // 开启一个线程监听信息，展示在textArea区域
        Context.threadPool().submitListener(new Runnable() {
            @Override
            public void run() {
                while (!Thread.interrupted()) {
                    rightInfo.append(Context.mailBox().acceptMessage());
                }
            }
        });

        jButton_generate.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if (0 == jComboBox_operateType.getSelectedIndex()) {
                    try {
                        downOutput.setText(UnitUtil.getUnitContext(topInput.getText()));
                    } catch (Exception e1) {
                        LogUtil.error(this, "生成失败", e1);
                        rightInfo.append(e1.getClass() + ":" + e1.getMessage());
                    }
                } else if (1 == jComboBox_operateType.getSelectedIndex()) {
                    final String path = getAndSetInputPath();
                    Context.threadPool().submitSingle(new Runnable() {
                        @Override
                        public void run() {
                            long now = System.currentTimeMillis();
                            Context.mailBox().sendMessage("批量读取java文件...");
                            FileUtil.batchReadFileByThread(path, new JavaFilter());
                            int count = FileUtil.batchCreateUnitContextFile();
                            long now2 = System.currentTimeMillis();
                            long seconds = (now2 - now) / 1000;
                            Context.mailBox().sendMessage("生成单元测试文件:" + count + "个，耗时:" + seconds + "秒,清单见:\"D:\\log\\list.txt\"!\n");
                        }
                    });
                } else if (2 == jComboBox_operateType.getSelectedIndex()) {
                    Context.threadPool().submitSingle(new Runnable() {
                        @Override
                        public void run() {
                            Context.mailBox().sendMessage("回滚开始...");
                            int count = FileUtil.rollBack("E:\\log\\list.txt");
                            Context.mailBox().sendMessage("回滚结束:" + count + "个文件已回滚!\n");
                        }
                    });
                } else {

                }
            }
        });

        jCheckBox_isPojo.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange() == ItemEvent.SELECTED) {
                    Context.config().setPojo(true);
                } else if (e.getStateChange() == ItemEvent.DESELECTED) {
                    Context.config().setPojo(false);
                } else {
                    throw new RuntimeException("你到了不可到达的区域，很神奇！");
                }
            }
        });

        jButton_open.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Context.threadPool().submitSingle(new Runnable() {
                    String path = getAndSetInputPath();

                    @Override
                    public void run() {
                        long time = System.currentTimeMillis();
                        Context.mailBox().sendMessage("容器开启...");
                        FileUtil.batchReadFileByThread(path, new JavaFilter());
                        Context.mailBox().sendMessage("容器开启完成，耗时:" + (System.currentTimeMillis() - time) + "ms");
                        Context.mailBox().sendMessage("容器包含类解析实例：" + Context.register().classDescSize() + "个\n");
                    }
                });
            }
        });


        jButton_choose.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JFileChooser chooser = new JFileChooser("");
                chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                chooser.setMultiSelectionEnabled(true);
                int open = chooser.showOpenDialog(null);
                if (JFileChooser.APPROVE_OPTION == open) {
                    String filePath = chooser.getSelectedFile().getAbsolutePath();
                    jText_inputpath.setText(filePath);
                    getAndSetInputPath();
                } else {
                    // doNoting
                }
            }
        });

        jComboBox_operateType.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                int chooseIndex = jComboBox_operateType.getSelectedIndex();
                // 先复位，避免勾选
                jCheckBox_isPojo.setSelected(false);
                if (chooseIndex == 0) {
                    jCheckBox_isPojo.setVisible(true);
                } else if (chooseIndex == 1 || chooseIndex == 2) {
                    jCheckBox_isPojo.setVisible(false); // 修改为隐藏
                } else {
                    // Dothing
                }
                // 将设置的状态置为false，避免批量生成时取值错误
                Context.config().setPojo(false);
            }
        });

        jButton_diy.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        ConfigFrame.singleton.setVisible(true);
                        ConfigFrame.singleton.setSpecClassDesc(Context.config().getSpecClassDesc());
                    }
                });
            }
        });
    }

    public String getAndSetInputPath() {
        String projectPath = jText_inputpath.getText();
        UserConfig.saveUserProjectPath(projectPath);
        return projectPath;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
//                SwingUtils.initDefaultUI();
            JFrame jFrame = SwingUtils.ofJFrameWithMenuBar("yinxue-unit", 1600, 900, new UnitPanel2());
            jFrame.setIconImage(new ImageIcon("icon/app_icon.png").getImage());
            jFrame.setVisible(true);
        });
    }

    public static void run() {
        SwingUtilities.invokeLater(() -> {
//                SwingUtils.initDefaultUI();
            JFrame jFrame = SwingUtils.ofJFrameWithMenuBar("yinxue-unit", 1280, 800, new UnitPanel2());
            jFrame.setIconImage(new ImageIcon("icon/app_icon.png").getImage());
            jFrame.setDefaultCloseOperation(HIDE_ON_CLOSE);
            jFrame.setVisible(true);
        });
    }


}